package com.zyd.config;

import com.zyd.context.HeaderContext;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;


@Configuration
public class FilterConfig {

    @Bean
    public FilterRegistrationBean headerFilterRegistration() {
        FilterRegistrationBean registrationBean = new FilterRegistrationBean();
        registrationBean.setFilter(new HeaderFilter());
        registrationBean.addUrlPatterns("/*");
        registrationBean.setName("headerFilter");
        registrationBean.setOrder(1);
        return registrationBean;
    }

    public class HeaderFilter implements Filter {


        @Override
        public void init(javax.servlet.FilterConfig filterConfig) throws ServletException {

        }

        @Override
        public void doFilter(ServletRequest srequest, ServletResponse response, FilterChain chain) throws IOException, ServletException {
            HttpServletRequest request = (HttpServletRequest) srequest;
            String userid = request.getHeader("UserId");
            HeaderContext.get().put("userid", userid);

            chain.doFilter(request, response);
        }

        @Override
        public void destroy() {

        }
    }

}
